package com.github.dynamic.datasource.configuration;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.github.dynamic.datasource.annotation.DataSourceAspectProcessor;
import com.github.dynamic.datasource.constant.DataSourceNameConstant;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DynamicDataSourceConfigAutoConfiguration {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.master")
    public DataSource masterDataSource(){
        return DruidDataSourceBuilder
                .create()
                .build();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.slave")
    public DataSource slaveDataSource(){
        return DruidDataSourceBuilder
                .create()
                .build();
    }

    @Bean
    @Primary
    public CustomDynamicDataSource dynamicRoutingDatasource(DataSource masterDataSource, DataSource slaveDataSource){
        Map<Object, Object> targetDatasource = new HashMap<>(2);
        targetDatasource.put(DataSourceNameConstant.MASTER, masterDataSource);
        targetDatasource.put(DataSourceNameConstant.SLAVE, slaveDataSource);

        return new CustomDynamicDataSource(masterDataSource, targetDatasource);
    }

    @Bean
    public DataSourceAspectProcessor dataSourceAspectProcessor(){
        return new DataSourceAspectProcessor();
    }

}
